<?php
/**
 * webappkit admin controller
 *
 * This file is part of Webappkit, a packages system for PHP web apps
 * @link http://webappkit.net
 * @package webappkit
 * @subpackage admin
 * @author J.Ducastel <nospam0@ducastel.name>
 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
 */


class WakAdminKit extends WakEngineKit {

    /**
     * admin home
     */
    function index() {
        // $this->_listKits();
        return true;
    }

    /**
     * admin installation
     * @return true
     * @todo trying to create tests database if dont exist
     */
    function install() {
        // first, check if already installed (security need)
        if ($this->_isInstalled()) {
            throw new WakEngineErrorPage("Webappkit is already installed", 403);
        }
        if ($this->response->request->isPost()) {
            // checking params
            $this->response->form = new WakInstallForm($_POST);
            if ($this->response->form->isValid()) {
                // new lines
                $nl = chr(13).chr(10);
                // getting clean data
                $data = $this->response->form->cleaned_data;
                // getting admin kit
                $adminKit = new WakKitFolder('webappkit.admin');
                // saving realm tool config with user
                $ini = '[realm]'.$nl
                .'name = "Webappkit Admin"'.$nl
                .'[users]'.$nl
                .'; identifiant = "mot de passe"'.$nl
                .$data['user']
                .' = "'.$data['pwd'].'"'.$nl;
                // saving realm config
                $adminKit->setToolIni('realm',$ini);
                // setting tests db config
                if (!$data['tests_no']) { // skipped by user
                // building INI
                    $ini = '[dblink]'.$nl
                    .'host = "'.$data['tests_host'].'"'.$nl
                    .'db = "'.$data['tests_db'].'"'.$nl
                    .'user = "'.$data['tests_user'].'"'.$nl
                    .'pwd = "'.$data['tests_pwd'].'"'.$nl
                    .'encoding = "'.$data['tests_encoding'].'"'.$nl;
                    // saving
                    $adminKit->setToolIni('db_tests', $ini);
                }
                // installed, rendering home page
                $this->response->view = 'index';
            }

            // echo "post !";
        } else {
            $this->response->form = new WakInstallForm();
        }
        return true;
    }

    /**
     * admin configuration
     */
    function configure() {

        // config form
    }

    /**
     * kits listing
     */
    public function kits() {
        // setting breadcrumb links
        $this->response->addBreadCrumb('Kits','kits');
        // listing kits
        $this->response->kits=array();
        foreach (Webappkit::listKits() as $id) {
            $this->response->kits[$id]=new WakKitFolder($id);
        }
        // echo '<pre>'; print_r($this->response->kits);
        return true;
    }

    /**
     * creates a kit
     * search for POST parent and name vars to build id
     *
     */
    public function create() {
        $id=$_POST['parent']?
        $_POST['parent'].'.'.$_POST['name']:$_POST['name'];
        $kit=new WakKitFolder($id);
        if ($kit->create()) {
            $this->_redirect('kit/'.$id);
            return true;
        }
        return false;
    }


    /**
     * return the unit tests database DbLinkTool
     * @return DbLinkTool
     */
    public function & getTestsDbLink() {
        return $this->db_tests;
    }

    /**
     * called before any request treatment
     * @return bool
     */
    protected function _setUp() {
        // i18n
        $this->response->chooseLangFrom(array('fr'),'fr');
        $this->templates->setCriteria('lang',$this->response->lang);
        // if not installed, then forward to install page
        if (!$this->_isInstalled()) {
            $this->_setAction('install');
            return true;
        }
        // auth
        // log in
        if (!$this->realm->login(true)) {
            throw new WakEngineErrorPage("auth required",401);
        }
        $this->response->user = $this->realm->getUser();
        // log out
        if (isset($_REQUEST['logout'])) {
            $this->realm->logout();
            throw new WakEngineErrorPage("logged out",401);
        }
        return true;
    }

    /**
     * fallback controller
     * called when we can't found a method to treat the request
     * @return bool
     */
    protected function _fallbackController() {
        // defining view
        $view=str_replace('/','.',$this->response->url->getPath());
        // checking for template
        if (!$this->templates->has($view)) {
            // no template => 404
            throw new WakEngineErrorPage("no page for $view",404);
        }

        $this->response->view=$view;
        return true;
    }/**/

    /**
     * checks if admin is cofnigured / installed
     */
    protected function _isInstalled() {
        return $this->toolHasConfig('realm');
    }

}
